package com.weasing.res.realm;

import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import com.weasing.res.dao.IWxAdminDao;
import com.weasing.res.dao.IWxPrivilegeDao;
import com.weasing.res.domain.WxAdmin;
import com.weasing.res.domain.WxPrivilege;

/**
 * shiro的用户认证和授权方法
 * 
 * @author long
 *
 */
public class RESRealm extends AuthorizingRealm {
	@Autowired
	private IWxAdminDao wxAdminDao;
	@Autowired
	private IWxPrivilegeDao wxPrivilegeDao;

	// 认证方法
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken token) throws AuthenticationException {
		System.out.println("自定义的realm中认证方法ing");
		UsernamePasswordToken passwordToken = (UsernamePasswordToken) token;
		// 获得页面输入的用户名
		String username = passwordToken.getUsername();
		// 根据用户名查询数据库中的密码
		WxAdmin wxAdmin = wxAdminDao.findUserByUsername(username);
		if (wxAdmin == null) {
			// 页面输入的用户名不存在
			return null;
		}
		// 简单认证信息对象
		AuthenticationInfo info = new SimpleAuthenticationInfo(wxAdmin,
				wxAdmin.getPassword(), this.getName());
		// 框架负责比对数据库中的密码和页面输入的密码是否一致
		return info;
	}

	// 授权方法
	protected AuthorizationInfo
			doGetAuthorizationInfo(PrincipalCollection principals) {
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		// 获取当前登录用户对象
		WxAdmin wxAdmin = (WxAdmin) SecurityUtils.getSubject().getPrincipal();
		List<WxPrivilege> list = null;
		if (wxAdmin.getUsername().equals("admin")) {
			list = wxPrivilegeDao.findAllByCriteria();
		} else {
			// ---------------------------------------------------------------
			list = wxPrivilegeDao.findPrivilegeByWxAdminId(wxAdmin);
			// ---------------------------------------------------------------
		}

		for (WxPrivilege wxPrivilege : list) {
			info.addStringPermission(wxPrivilege.getUrl());
		}
		return info;
	}
}
